package com.future;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: 290. 单词规律
 * <p>
 * "abba"
 * "dog dog dog dog"
 * false
 *
 * @author weiruibai.vendor
 * Date: 2023/2/21 10:35
 */
public class Solution_290 {

    private static Solution_290 instance = new Solution_290();

    public static void main(String[] args) {
        String pattern = "abba";
        String s = "dog cat cat dog";
        pattern = "aaaa";
        s = "dog cat cat dog";
        pattern = "abba";
        s = "dog dog dog dog";
        System.out.println(instance.wordPattern(pattern, s));
    }

    /**
     * pattern中的同一个字符对应同一个字符串，不同字符必须对应不同字符串
     * pattern = "abba";
     * s = "dog dog dog dog";
     * a-->dog
     * 这时b->dog不对了
     *
     * @param pattern
     * @param s
     * @return
     */
    public boolean wordPattern(String pattern, String s) {
        int N = pattern.length();
        if (N == 1) {
            return s.split(" ").length == 1;
        }
        String[] arr = s.split(" ");
        if (N != arr.length) {
            return false;
        }
        Map<Character, String> map = new HashMap<>();
        for (int i = 0; i < N; i++) {
            String str = map.get(pattern.charAt(i));
            if (null == str) {
                if (map.values().contains(arr[i])) {
                    /**
                     * eg
                     *  pattern = "abba";
                     *  s = "dog dog dog dog";
                     *  a-->dog
                     *  b-->dog
                     *  不满足
                     *  不同字母对应不同的字符串！！！
                     */
                    return false;
                }
                map.put(pattern.charAt(i), arr[i]);
            } else {
                if (!str.equals(arr[i])) {
                    return false;
                }
            }
        }
        return true;
    }

}
